package com.an.vhr.controller;

import com.an.vhr.bean.Hr;
import com.an.vhr.bean.RespBean;
import com.an.vhr.service.HrService;
import com.an.vhr.utils.FastDFSUtil;
import com.an.vhr.utils.HrUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author: an1089
 **/
@RestController
public class HrInfoController {
    @Resource
    HrService hrService;
    @GetMapping("/hr/info")
    public Hr getHrInfo(){
        return HrUtils.getCurrentHr();
    }

    @PutMapping("/hr/info")
    public RespBean updateHrInfo(@RequestBody Hr hr, Authentication authentication){
        if(hrService.updateHr(hr) == 1){
            SecurityContextHolder.getContext()
                    .setAuthentication(new UsernamePasswordAuthenticationToken(hr,authentication.getCredentials(),authentication.getAuthorities()));
            return RespBean.ok("更新成功");
        }
        return RespBean.ok("更新失败");
    }

    @PutMapping("/hr/password")
    public RespBean updateHrPassword(@RequestBody Map<String,String> map){
        String oldPass = map.get("oldpass");
        String newPass = map.get("pass");
        String hrid = map.get("hrid");
        if(!hrid.equals(HrUtils.getCurrentHr().getId().toString())){
            return RespBean.error("身份异常请联系管理员");
        }
        Integer res = hrService.updateHrPassword(oldPass, newPass, hrid);
        if( res == 1){
            return RespBean.ok("更新成功");
        }else if (res == 2){
            return RespBean.ok("旧密码错误");
        }
        return RespBean.ok("更新失败");
    }

    @PostMapping("/hr/userface")
    private RespBean updateHrUserFace(MultipartFile file, Integer id,Authentication authentication){
        String upload = FastDFSUtil.upload(file);
        if(hrService.updateHrUserFace(upload,id) == 1){
            Hr hr = (Hr) authentication.getPrincipal();
            hr.setUserface(upload);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(hr,authentication.getCredentials(),authentication.getAuthorities()));
            return RespBean.ok("更新成功");
        }
        return RespBean.ok("更新失败");
    }
}
